import {isObject} from "./isObject";
import {isFunction} from "./isFunction";
import {isDate} from "./isDate";
import {isRegExp} from "./isRegExp";
import {isElement} from "./isElement";
import {isArray} from "./isArray";

function baseExtend(dst, objs, deep): any {
  // console.log(dst,objs)
  for (let i = 0, ii = objs.length; i < ii; ++i) {
    let obj = objs[i];
    if (!isObject(obj) && !isFunction(obj)) continue;
    let keys = Object.keys(obj);
    for (let j = 0, jj = keys.length; j < jj; j++) {
      let key = keys[j];
      let src = obj[key];
      if (deep && isObject(src)) {
        if (isDate(src)) {
          dst[key] = new Date(src.valueOf());
        } else if (isRegExp(src)) {
          dst[key] = new RegExp(src);
        } else if (src.nodeName) {
          dst[key] = src.cloneNode(true);
        } else if (isElement(src)) {
          dst[key] = src.clone();
        } else {
          if (!isObject(dst[key])) dst[key] = isArray(src) ? [] : {};
          baseExtend(dst[key], [src], true);
        }
      } else {
        dst[key] = src;
      }
    }
  }
  return dst;
}

function extend(source, overwrites, deep = true): any {
  return baseExtend(source, overwrites instanceof Array ? overwrites : [overwrites], deep);
}

export {extend}
